import 'package:diary/util/shared_pref_util.dart';
import 'package:flutter/cupertino.dart';

import '../../main.dart';
import '../../router/routes.dart';

class AppConfigurationPage extends StatefulWidget {
  const AppConfigurationPage({Key? key}) : super(key: key);

  @override
  State<AppConfigurationPage> createState() => _AppConfigurationPageState();
}

class _AppConfigurationPageState extends State<AppConfigurationPage> {
  final TextEditingController _nameInputController = TextEditingController();

  // 资料填写区域
  Widget _buildInputForm() {
    return CupertinoTextField(
      placeholder: "您的名字",
      keyboardType: TextInputType.name,
      controller: _nameInputController,
    );
  }

  // 底部确认按钮
  Widget _buildConfirmButton() {
    return CupertinoButton(
        child: const Text("继续"),
        onPressed: () {
          // 保存资料到首选项，并跳转到主页
          _saveToSharedPref();
        });
  }

  void _saveToSharedPref() async {
    var name = _nameInputController.text;
    // 空字符串判断
    if (name == "") {
      showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: const Text("请检查"),
            content: const Text("请填写您的名字"),
            actions: [
              CupertinoDialogAction(
                child: const Text("确定"),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    } else {
      // 保存资料到首选项
      SharedPrefUtil.instance.saveUsername(name);
      // 跳转到主页
      router.navigateTo(context, Routes.indexPage, clearStack: true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: CupertinoPageScaffold(
        navigationBar: const CupertinoNavigationBar(
          middle: Text("个人资料配置"),
        ),
        child: SafeArea(
          child: Container(
            margin: const EdgeInsets.all(50),
            child: Column(
              children: [
                Expanded(
                    child: Center(
                  child: _buildInputForm(),
                )),
                _buildConfirmButton()
              ],
            ),
          ),
        ),
      ),
    );
  }
}
